package com.hqbzl.c1.volatiles;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

@Slf4j
public class TestVolatile {
    public static void main(String[] args) {
        TestVolatile t = new TestVolatile();
        t.start();
        sleep(10);
        t.stop();
    }

    private volatile boolean starting = false;
    private volatile boolean stop = false;
    private Thread thread;

    private static void sleep(long t) {
        try {
            TimeUnit.SECONDS.sleep(t);
        } catch (InterruptedException e) {
            e.printStackTrace();
            Thread.currentThread().interrupt();
        }
    }

    public void start() {
        synchronized (this) {
            log.debug("thread starting: {}", starting);
            if (starting) {
                return;
            }
            starting = true;
        }
        //do someThing
        thread = new Thread(() -> {
            while (!stop) {
                log.debug("thread runing");
                sleep(1);
            }
            starting = false;
            log.debug("thread stop: {}", stop);
        }, "th1");
        thread.start();
    }

    public void stop() {
        stop = true;
        log.debug("read stop thread: {}", stop);
        thread.interrupt();
    }

}
